package com.magnate.software.spring.redis.dao.impl;

import com.magnate.software.domain.po.User;
import com.magnate.software.spring.redis.dao.UserRedisDao;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户Redis操作实现
 *
 * @author WangYang
 * @version 1.0
 * @datetime 2015/9/29 16:44
 */
@Service(" userRedisDao")
public class UserRedisDaoImpl implements UserRedisDao {

    private final static String OBJECT_KEY = "wy:user:{0}";

    @Resource
    private RedisTemplate msgPackRedisTemplate;

    @Override
    public boolean save(User user) {
        msgPackRedisTemplate.opsForValue().set(MessageFormat.format(OBJECT_KEY, user.getPhone()), user);
        return true;
    }

    @Override
    public User getUser(String phone) {
        return (User) msgPackRedisTemplate.opsForValue().get(MessageFormat.format(OBJECT_KEY, phone));
    }

    @Override
    public List<User> getUsers(List<String> phones) {
        List<String> keys = new ArrayList<>();
        for (String phone : phones) {
            keys.add(MessageFormat.format(OBJECT_KEY, phone));
        }
        return msgPackRedisTemplate.opsForValue().multiGet(keys);
    }

    @Override
    public boolean update(User user) {
        msgPackRedisTemplate.opsForValue().set(MessageFormat.format(OBJECT_KEY, user.getPhone()), user);
        return false;
    }

    @Override
    public boolean delete(String phone) {
        msgPackRedisTemplate.delete(MessageFormat.format(OBJECT_KEY, phone));
        return true;
    }
}
